<?php

namespace App\Services\Stats\Summary\Elasticsearch;

use App\Services\Service;
use App\Services\Traits\DatabaseElasticsearch;
use App\Models\Elasticsearch\Settlement\Info as SettlementInfo;
use App\Core\Traits\Numeral;

class DocCountService extends Service
{
    use DatabaseElasticsearch, Numeral;

    /**
     * 制作统计参数
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    private function makeAggParams($request)
    {
        $datetime = $this->getParamArray($request, 'datetime');

        return [
            'body' => [
                'size' => 0,
                'aggs' => [
                    'group_time' => [
                        'date_histogram' => [
                            'field' => 'end_time_at',
                            'time_zone' => '+08:00',
                            'calendar_interval' => '1d',
                            'format' => 'yyyy-MM-dd',
                            'min_doc_count' => 0,
                            'extended_bounds' => [
                                'min' => $datetime[0] * 1000,
                                'max' => $datetime[1] * 1000,
                            ],
                        ],
                    ],
                ]
            ]
        ];
    }

    /**
     * 获取排行数据
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function getTopList($request)
    {
        // 制作统计参数
        $params = $this->makeAggParams($request);

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $params);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $params, 'end_time');

        // 查询数据
        $results = SettlementInfo::search($params);

        // 制作数据
        $data = $times = [];
        foreach ($results['aggregations']['group_time']['buckets'] ?? [] as $item) {
            // 数据轴
            $data[] = $item['doc_count'];
            // 时间轴
            $times[] = $item['key_as_string'];
        }

        return [
            'data' => $data,
            'times' => $times,
        ];
    }
}
